package cn.com.xinjinfu.pdoulcProduct.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.TransactHostBean.DealRecord.Page;
import cn.com.xinjinfu.pdoulcProduct.entity.TransactHostBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView.IXListViewListener;

/**
 * 交易明细
 * Created by android-adt on 2016/1/7.
 */
public class ActTransactionDetailed extends BaseActivity implements OnClickListener,IXListViewListener  {
    private int currPage;
    private XListView mListView;
    private Handler mHandler;
    private RequestQueue requen;
    private TransactHostBean transactHostBean;
    private MyAdapter mAdapter;
    private  List<Page> page;
    private TextView top_title_tv;
    private ImageView img_select;
    private RelativeLayout top_left_icon;
    private LinearLayout no_invest_view;
    private PopupWindow popupwindow;
    private boolean[] bools;
    private int type;
    private Dialog dg;
    private Button quanbu,tixian,chongzhi,touzi,huikuan,jiangli;
    private final String ACTION_NAME = "跳转首页广播";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_transaction_detailed);
        currPage = 1;
        //初始化头布局
        top_title_tv = (TextView) findViewById(R.id.top_title_tv);
        top_left_icon = (RelativeLayout) findViewById(R.id.top_left_icon);
        img_select = (ImageView) findViewById(R.id.img_select);
        no_invest_view = (LinearLayout) findViewById(R.id.no_invest_view);
        top_title_tv.setOnClickListener(this);
        top_left_icon.setOnClickListener(this);
        bools= new boolean[]{true, false, false, false, false, false};
        mListView = (XListView) findViewById(R.id.lv_detailed);
        mListView.setPullLoadEnable(true);// 是否显示下拉刷新和上啦加载
        mListView.setPullRefreshEnable(false);
        mAdapter = new MyAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setXListViewListener(this);
        mHandler = new Handler();
        requen = Volley.newRequestQueue(this);
        loginRequest(0, currPage);
    }

    /***
     * 筛选框
     */
    private void showSelectDialog() {
         // 获取自定义布局文件pop.xml的视图
        View customView = getLayoutInflater().inflate(R.layout.select_detailed_popview,
                null, false);
        // 屏幕宽度（像素）
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels;
        // 创建PopupWindow实例
        popupwindow = new PopupWindow(customView, width, height);
        /** 在这里可以实现自定义视图的功能 */
        quanbu = (Button) customView.findViewById(R.id.quanbu);
        tixian = (Button) customView.findViewById(R.id.tixian);
        chongzhi = (Button) customView.findViewById(R.id.chongzhi);
        touzi = (Button) customView.findViewById(R.id.touzi);
        huikuan = (Button) customView.findViewById(R.id.huikuan);
        jiangli = (Button) customView.findViewById(R.id.jiangli);

        quanbu.setOnClickListener(this);
        tixian.setOnClickListener(this);
        chongzhi.setOnClickListener(this);
        touzi.setOnClickListener(this);
        huikuan.setOnClickListener(this);
        jiangli.setOnClickListener(this);
        setBools(8);//此是要显示保存的状态信息，值务必要大于7
    }

    /***
     * 通过boolan数组来展示筛选按钮的 状态
     * @param x
     */
    public void setBools(int x){
        if (x<7){
            for(int i = 0; i < bools.length; i++){
                bools[i] = false;
            }
            bools[x] = true;
        }
        quanbu.setSelected(bools[0]);
        tixian.setSelected(bools[1]);
        chongzhi.setSelected(bools[2]);
        touzi.setSelected(bools[3]);
        huikuan.setSelected(bools[4]);
        jiangli.setSelected(bools[5]);
        currPage = 1;
        loginRequest(x, currPage);
    }

    @Override
    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        switch (v.getId()) {
            case R.id.top_title_tv:
                if (popupwindow != null&&popupwindow.isShowing()) {
                    popupwindow.dismiss();
                    img_select.setSelected(false);
                } else {
                    showSelectDialog();
                    popupwindow.showAsDropDown(v, 0, 20);
                    img_select.setSelected(true);
                }
                break;
            case R.id.top_left_icon:
                closePopwindow();
                onBackPressed();
                break;
            case R.id.quanbu:
                setBools(0);
                closePopwindow();
                break;
            case R.id.tixian:
                setBools(1);
                closePopwindow();
                break;
            case R.id.chongzhi:
                setBools(2);
                closePopwindow();
                break;
            case R.id.touzi:
                setBools(3);
                closePopwindow();
                break;
            case R.id.huikuan:
                setBools(4);
                closePopwindow();
                break;
            case R.id.jiangli:
                setBools(5);
                closePopwindow();
                break;
            default:
                break;
        }
    }

    /**
     * 购买成功后可跳转到此页，要指定返回到我的p兜fragment
     */
    @Override
    public void onBackPressed() {
            Intent mIntent = new Intent(ACTION_NAME);
            mIntent.putExtra("yaner", "mPdou");
            sendBroadcast(mIntent);
        finish();
    }

    public void closePopwindow(){
        if (popupwindow != null && popupwindow.isShowing()) {
            popupwindow.dismiss();
            popupwindow = null;
            img_select.setSelected(false);
        }
    }
    /**
     * 网络请求
     */
    private void loginRequest(int type,int currPage) {
        if (currPage == 1){
            dg = UIManager.getLoadingDialog(this);
            dg.setCanceledOnTouchOutside(false);
            dg.show();
        }
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1007");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("currPage", currPage+"");
            parameters.put("pageSize", "9");
            parameters.put("type", type+"");
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            requen.add(request);
        }

    }
    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActTransactionDetailed.this, error);
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            transactHostBean = JSON.parseObject(jobj.toString(), TransactHostBean.class);
            type = transactHostBean.getDealRecord().getConditions().getType();
            page = transactHostBean.getDealRecord().getPage();
            if (currPage == 1){
                if (page.isEmpty()){
                    no_invest_view.setVisibility(View.VISIBLE);
                    mListView.setPullLoadEnable(false);
                } else {
                    mListView.setPullLoadEnable(true);
                    no_invest_view.setVisibility(View.GONE);}
                mAdapter.setList(page);
            }
            else {
                if (page.isEmpty()) {
                    ToastManager.showShort(ActTransactionDetailed.this, "没有更多数据");
                } else {
                    mAdapter.addList(page);
                }
            }
        }
    };

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }


    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loginRequest(type,1);
                onLoad();
            }
        }, 1000);
    }

    /**
     * 上啦加载
     */
    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                currPage++;
                loginRequest(type,currPage);
                onLoad();
            }
        }, 1000);
    }

    private class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private List<Page> list;

        private DateFormat sdf;
        public MyAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
            list = new ArrayList<>();
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        public void setList(List<Page> list) {
            this.list.clear();
            this.list.addAll(list);
            notifyDataSetChanged();
        }
        public void addList(List<Page> list) {
            this.list.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_transaction_detailed, null);
                holder = new ViewHolder();
                holder.tv_detailed_title = (TextView) convertView.findViewById(R.id.tv_detailed_title);
                holder.tv_detailed_time = (TextView) convertView.findViewById(R.id.tv_detailed_time);
                holder.tv_detailed_money = (TextView) convertView.findViewById(R.id.tv_detailed_money);
                convertView.setTag(holder);//绑定ViewHolder对象
            } else {
                holder = (ViewHolder) convertView.getTag();//取出ViewHolder对象
            }
            Page page = list.get(position);
            if (page != null) {
                if (page.getType()==1){
                    holder.tv_detailed_money.setTextColor(0xFF339900);
                    holder.tv_detailed_money.setText("+"+TextViewUtil.getSumLength(page.getAmount()));
                }else if (page.getType()==2){
                    holder.tv_detailed_money.setTextColor(0xFFFF0000);
                    holder.tv_detailed_money.setText("-"+TextViewUtil.getSumLength(page.getAmount()));
                }else {
                    holder.tv_detailed_money.setTextColor(0xFF333333);
                    holder.tv_detailed_money.setText(TextViewUtil.getSumLength(page.getAmount()));
                }
//                else if (page.getType()==3){
//                    holder.tv_detailed_money.setTextColor(0xFF333333);
//                    holder.tv_detailed_money.setText(TextViewUtil.getSumLength(page.getAmount()));
//                }else if (page.getType()==4){
//                    holder.tv_detailed_money.setTextColor(0xFF333333);
//                    holder.tv_detailed_money.setText(TextViewUtil.getSumLength(page.getAmount()));
//                }
                holder.tv_detailed_title.setText(page.getName());
                holder.tv_detailed_time.setText(sdf.format(page.getTime()));
            }
            return convertView;
        }
    }
    public final class ViewHolder {
        public TextView tv_detailed_title;
        public TextView tv_detailed_time;
        public TextView tv_detailed_money;
    }

}
